package com.zmj.framework.handler.exception;

import cn.hutool.core.util.ObjectUtil;
import com.zmj.framework.response.ResponseCode;
import com.zmj.framework.response.Result;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ExceptionMapperUtil {

    public static Result buildBody(Exception exception, ResponseCode responseCode) {
        log.info("==> error:{}",exception);
        return buildBody(exception,responseCode.getCode(),responseCode.getMsg()+":"+exception.getMessage());
    }

    public static Result buildBody(Exception exception, int resultCode) {
        log.info("==> error:{}",exception);
        return buildBody(exception,resultCode,exception.getMessage());
    }

    private static Result buildBody(Exception exception,int resultCode,String msg) {
        //TODO if exception.getMessage非自定义，使用通用异常说明
        Result resultBody = Result.fail(resultCode,msg);
        log.error("==> error:{} exception: {}",resultBody, exception);
        return resultBody;
    }

    public static boolean checkException(Exception ex,String exceptionName,int count) {
        //只往下找三层
        if(count > 3) {
            return false;
        }
        String className = ex.getClass().getName();
        if(className.contains(exceptionName)) {
            return true;
        }
        if (ObjectUtil.isNotNull(ex.getCause())) {
            return checkException(ex,exceptionName,++count);
        } else {
            return false;
        }
    }
}
